﻿#ifndef SLTOOL_TIMER_20220103_
#define SLTOOL_TIMER_20220103_

#include <chrono>
//#include <functional>
//#include <thread>
#include <stdint.h>
#ifdef WIN32
//#include <sys/timeb.h>
#include <time.h>
#else
#include <sys/time.h>
#endif

#include "SLT_tool_pub_def.h"

typedef uint64_t SLT_TIMER_HANDLE;
#define SLT_TIMER_HANDLE_INVLAID  0

enum SLT_timer_CallBackType
{
	SLT_timerDue = 0,		// 时间到期
	SLT_timerCancel,		// 取消
};
typedef	void(*SLT_timerTimeOut)(SLT_timer_CallBackType _type, SLT_TIMER_HANDLE timerid, void* userData);
//返回timerid, 返回0表示失败
//单位 毫秒
//periodic true- 周期性定时器，false-一次性定时器  //没有实现
SLT_API int SLT_setTimer(SLT_TIMER_HANDLE &_th, int _intervalMs, bool periodic, SLT_timerTimeOut _fun,void* _userData);
//取消timer  //未实现
//SLT_API void SLT_cancelTimer(SLT_TIMER_HANDLE _h);

//
#define SLT_sleep(_ms) std::this_thread::sleep_for(std::chrono::milliseconds(_ms))
#define SLT_getSteadyTimeMs()  std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()
#define SLT_getSystemNow()   std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())

SLT_API void SLT_getTimeOfDay(struct timeval *_time);
//snprintf(buf, sizeof(buf), "%d-%02d-%02d %02d:%02d:%02d",1900 + ltm.tm_year, 1 + ltm.tm_mon, ltm.tm_mday, ltm.tm_hour, ltm.tm_min, ltm.tm_sec);
SLT_API void SLT_localTime(time_t timep, struct tm* result);

//流逝时间
typedef std::chrono::steady_clock::time_point SLT_elapseTimeType;
#define  SLT_elapseTime_now() std::chrono::steady_clock::now()
class SLT_elapseTimer
{
public:
	SLT_elapseTimer()
	{
		m_start = std::chrono::steady_clock::now();
	}
	SLT_elapseTimer& operator=(SLT_elapseTimer& _r) {
		if (this != &_r) {
			this->m_start = _r.m_start;
		}
		return *this;
	}
	void start()
	{
		m_start = std::chrono::steady_clock::now();
	}
	int64_t elapseMs(const std::chrono::steady_clock::time_point &_now = SLT_elapseTime_now())
	{
		auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(_now - m_start);
		return duration.count();
	}
private:
	std::chrono::steady_clock::time_point m_start;
};

#endif